﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Serilog.Core;
using Serilog.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace ChatBackend.Common.Logs
{
    public class RequestEnricher: ILogEventEnricher
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

        public RequestEnricher(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            var context = _httpContextAccessor.HttpContext;
            if (context == null || context.Connection == null || context.Request == null)
            {
                return;
            }
            var ipAddress = context.Connection.RemoteIpAddress?.ToString();
            if (!string.IsNullOrEmpty(ipAddress))
            {
                logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("IpAddress", ipAddress));
            }
            var requestHost = context.Request.Host.Value;
            if (!string.IsNullOrEmpty(requestHost))
            {
                logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("RequestHost", requestHost));
            }
            var requestScheme = context.Request.Scheme;
            if (!string.IsNullOrEmpty(requestScheme))
            {
                logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("RequestScheme", requestScheme));
            }
            var requestUrl = context.Request.GetDisplayUrl();
            if (!string.IsNullOrEmpty(requestUrl))
            {
                logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("RequestUrl", requestUrl));
            }
            if (context?.User != null)
            {
                var userId = context.User.FindFirstValue("sub");
                if (!string.IsNullOrEmpty(userId))
                {
                    logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("UserId", userId));
                }
                var userName = context.User.Identity?.Name;
                if (!string.IsNullOrEmpty(userName))
                {
                    logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("UserName", userName));
                }
            }
        }
    }
}
